import React, { useState } from 'react';
import { RouteComponentProps, useHistory } from 'react-router-dom';
import { Header, Footer } from '../../components';
import './index.less';
import {
  Form,
  Input,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  PageHeader,
  Steps,
  notification,
} from 'antd';
import { getCaptcha, register } from '../../http/api';
// import { useSelector } from '../../redux/hooks';
// import { useDispatch } from 'react-redux';
// import { giveMeDataActionCreator } from '../../redux/recommendProducts/recommendProductsActions';
interface MatchParams {}
const { Step } = Steps;
const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 5,
    },
  },
};
export const Register: React.FC<RouteComponentProps<MatchParams>> = (props) => {
  // const dispatch = useDispatch();
  // const loading = useSelector(
  //   (state) => state.recommendProductsReducer.loading
  // );
  // const error = useSelector((state) => state.recommendProductsReducer.error);
  // const productList = useSelector(
  //   (state) => state.recommendProductsReducer.productList
  // );
  const [form] = Form.useForm();
  const [captchaTime, setCaptchaTime] = useState('获取验证码');
  const history = useHistory();

  // 提交表单
  const onFinish = (values: any) => {
    var data = {
      mobile: values.phone,
      code: values.captcha,
      truename: values.nickname,
      password: values.password,
      repassword: values.confirm,
      recode: values.Invitational,
    };
    register(data).then((res: any) => {
      if (res.code !== 1) {
        return notification.info({
          message: ``,
          description: res.msg,
        });
      }
      notification.success({
        message: ``,
        description: '注册成功',
      });
      setTimeout(() => {
        history.push('/login');
      }, 1000);
    });
  };

  const prefixSelector = (
    <Form.Item name='prefix' noStyle>
      <Select style={{ width: 70 }}>
        <Option value='86'>+86</Option>
        <Option value='87'>+87</Option>
      </Select>
    </Form.Item>
  );

  // 获取验证码相关
  const getcaptcha = () => {
    if (captchaTime !== '获取验证码') {
      return;
    }
    const value = form.getFieldValue('phone');
    if (!value) {
      return notification.info({
        message: ``,
        description: '请输入手机号码',
      });
    }
    const regu = '^1[0-9]{10}$';
    const re = new RegExp(regu);
    if (!re.test(value)) {
      return notification.info({
        message: ``,
        description: '请输入正确的手机号码',
      });
    }

    getCaptcha({
      mobile: value,
      type: '1',
    }).then((res: any) => {
      if (res.code !== 1) {
        return notification.info({
          message: ``,
          description: res.msg,
        });
      }
      notification.success({
        message: ``,
        description: res.msg,
      });
      console.log(res);
      let time = 60;
      const interval = setInterval(() => {
        time--;
        setCaptchaTime(`${time}s后获取`);
        if (time === 0) {
          time = 60;
          setCaptchaTime('获取验证码');
          clearInterval(interval);
        }
      }, 1000);
    });
  };

  // const ceshiya = () => {
  //   dispatch(giveMeDataActionCreator());
  //   console.log(loading);
  //   console.log(error);

  //   setTimeout(() => {
  //     console.log(productList);
  //   });
  // };

  return (
    <div className='registerbox'>
      <Header></Header>

      <div className='register'>
        <PageHeader className='site-page-header' title='用户注册' subTitle='' />
        <Steps current={0} className='step' size='small'>
          <Step title='填写账号信息' description='' />
          <Step title='注册成功' description='' />
        </Steps>
        <Form
          {...formItemLayout}
          form={form}
          name='register'
          onFinish={onFinish}
          initialValues={{
            prefix: '86',
            agreement: true,
          }}
          scrollToFirstError
        >
          <Form.Item
            name='nickname'
            label='姓名'
            rules={[
              {
                required: true,
                message: '请输入姓名!',
                whitespace: true,
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name='phone'
            label='手机号'
            rules={[
              { required: true, message: '请输入您的手机号码!' },
              {
                validator: async (rule, value) => {
                  if (!value) {
                    return;
                  }
                  const regu = '^1[0-9]{10}$';
                  const re = new RegExp(regu);
                  if (re.test(value)) {
                  } else {
                    throw new Error('请输入正确的手机号码!');
                  }
                },
              },
            ]}
          >
            <Input addonBefore={prefixSelector} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name='captcha'
            label='验证码'
            rules={[
              { required: true, message: '请输入验证码!' },
              {
                validator: async (rule, value) => {
                  if (!value) {
                    return;
                  }
                  const regu = '^[0-9]{6}$';
                  const re = new RegExp(regu);
                  if (re.test(value)) {
                  } else {
                    throw new Error('请输入6位纯数字！');
                  }
                },
              },
            ]}
          >
            <Row gutter={6}>
              <Col span={20}>
                <Form.Item name='captcha' noStyle>
                  <Input />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Button className='getcaptcha' onClick={getcaptcha}>
                  {captchaTime}
                </Button>
              </Col>
            </Row>
          </Form.Item>
          <Form.Item
            name='password'
            label='设置密码'
            rules={[
              {
                required: true,
                message: '请输入密码!',
              },
              {
                validator: async (rule, value) => {
                  if (!value) {
                    return;
                  }
                  const regu = '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$';
                  const re = new RegExp(regu);
                  if (re.test(value)) {
                  } else {
                    throw new Error('密码至少包含 数字和英文，长度8-20!');
                  }
                },
              },
            ]}
            hasFeedback
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name='confirm'
            label='确认密码'
            dependencies={['password']}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请输入确认密码!',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次密码不一致!'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item name='Invitational' label='邀请码' tooltip='非必填字段'>
            <Input />
          </Form.Item>
          <Form.Item
            name='agreement'
            valuePropName='checked'
            rules={[
              {
                validator: (_, value) =>
                  value
                    ? Promise.resolve()
                    : Promise.reject(new Error('请阅读并勾选用户许可')),
              },
            ]}
            {...tailFormItemLayout}
          >
            <Checkbox>
              我已阅读并同意 <a href='/userRead'> 《车云链平台用户许可》 </a>
            </Checkbox>
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button type='primary' htmlType='submit' block>
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Footer></Footer>
    </div>
  );
};
